package demo2;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import demo2.vo.Multi;

/**
 * 短信验证码发送器
 */
public final class SmsSubMailSender {
    /**
     *
     */
    private static final String APPID = "appid";
    /**
     *
     */
    private static final String PROJECT = "project";
    /**
     *
     */
    private static final String MULTI = "multi";
    /**
     *
     */
    private static final String TO = "to";
    
    private static final String VARS = "vars";
    /**
     *
     */
    private static final String SIGNATURE = "signature";
    /**
     *SIGNATURE
     */
    private static final String SIGNATURE_VALUE = "a5dcd284d44d71288e5bc8b582a53882";
    /**
     *APPID
     */
    private static final String APPID_VALUE = "11093";
    /**
     * 正式短信记得修改项目号
     */
    private static final String PROJECT_VALUE = "t97o72";
    /**
     *短信一对一地址
     */
    private static final String XSEND_API_URL = "https://api.submail.cn/message/xsend.json";
    /**
     *短信一对多地址
     */
    private static final String MULTIXSEND_API_URL = "https://api.submail.cn/message/multixsend.json";
    /**
     * 发送超长报文增长超时时间
     */
    private static int CONNECT_TIMEOUT = 30 * 1000;
    private static RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(CONNECT_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(CONNECT_TIMEOUT).build();
    private CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();

    private String buildMsg(Object msd) {
        
        return JSONUtil.toShortJson(msd);
    }

    private static Multi buildMulti(HashMap<String, Object> vars, String phoneNumber) {
        Multi multi = new Multi();
        multi.setTo(phoneNumber);
        multi.setVars(vars);
        return multi;
    }

    /**
     * 一对多发送
     * @param multi
     * @return
     */
    public boolean msgMultiSend(List<Multi> multi) {
        try {
            HashMap<String, Object> request_map = new HashMap<>();
            request_map.put(APPID, APPID_VALUE);
            request_map.put(PROJECT, PROJECT_VALUE);
            request_map.put(MULTI, buildMsg(multi));
            request_map.put(SIGNATURE, SIGNATURE_VALUE);
            boolean request = request(MULTIXSEND_API_URL, request_map);
            if (request) {
                //LOG.debug("发送成功！");
                return true;
            } else {
               // LOG.debug("发送失败！");
                return false;
            }
        } catch (Exception e) {
           // LOG.error("出现异常！发送失败！");
           // LOG.error(e.toString());
            return false;
        }
    }
    
    /**
     * 一对一发送
     * @param number
     * @param code
     * @return
     */
    public boolean msgSend(String number,Map<String, Object> vars) {
    	try {
    		HashMap<String, Object> request_map = new HashMap<>();
    		request_map.put(APPID, APPID_VALUE);
    		request_map.put(PROJECT, PROJECT_VALUE);
    		request_map.put(TO, number);
    		request_map.put(VARS, buildMsg(vars));
    		request_map.put(SIGNATURE, SIGNATURE_VALUE);
    		boolean request = request(XSEND_API_URL, request_map);
    		if (request) {
    			//LOG.debug("发送成功！");
    			return true;
    		} else {
    			// LOG.debug("发送失败！");
    			return false;
    		}
    	} catch (Exception e) {
    		// LOG.error("出现异常！发送失败！");
    		// LOG.error(e.toString());
    		return false;
    	}
    }

    private boolean request(String url, Map<String, Object> data) {
        HttpPost httppost = new HttpPost(url);
        httppost.addHeader("charset", "UTF-8");
        httppost.setEntity(build(data));
        try {
            HttpResponse response = closeableHttpClient.execute(httppost);
//            HttpResponse response = null;
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                String jsonStr = EntityUtils.toString(httpEntity, "UTF-8");
//                System.out.println(jsonStr);
               
                return jsonStr.contains("success");
            }
            closeableHttpClient.close();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * Transform the request data to HttpEntity
     *
     * @param data
     * @return HttpEntity
     */
    private HttpEntity build(Map<String, Object> data) {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addTextBody(APPID, APPID_VALUE);
//		builder.setCharset(Charset.);
        data.put(APPID, APPID_VALUE);
        ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
        builder.addTextBody(SIGNATURE, SIGNATURE_VALUE, contentType);
        for (Map.Entry<String, Object> entry : data.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof String) {
                builder.addTextBody(key, String.valueOf(value), contentType);
            } else if (value instanceof File) {
                builder.addBinaryBody(key, (File) value);
            }
        }
        return builder.build();
    }

    /**
     * 测试
     *
     * @param args
     */
    public static void main(String args[]) {
        SmsSubMailSender sender = new SmsSubMailSender();
        try {
        	
        	//1.一对多发送
        	List<Multi> multis = new ArrayList<>();
        	multis.add(buildMulti(new HashMap<String, Object>() {{
                put("code", "1234");
            }}, "15901333487"));
        	multis.add(buildMulti(new HashMap<String, Object>() {{
        		put("code", "5678");
        	}}, "15901333487"));
            boolean result = sender.msgMultiSend(multis);
            System.out.printf("result:" + result);
            System.out.printf("\n");
            
            //2.一对一发送
            Map<String, Object> vars= new HashMap<String, Object>();
            vars.put("code", "9875");	
            boolean result2 = sender.msgSend("15901333487", vars);
            System.out.printf("result:" + result2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
